<template>
    <div>
        <el-card shadow="never">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                :option="tableOption"
                :fetch-params="state.searchParams"
                :fetch-api="fetch()">
                <template #headerOperate>
                    <el-button type="primary" @click="newImport('')">新建对接</el-button>
                </template>
            </ZwTable>
            <Dialog :app-dialog="appDialog">
                <el-form ref="ruleForm" :model="form" label-width="auto" class="addForm" :rules="rules">
                    <el-form-item label="规则名称" prop="name">
                        <el-input
                            v-model="form.name"
                            placeholder="请输入规则名称"
                            maxlength="8"
                            show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item prop="seas_id" label="客户公海 ">
                        <el-select v-model="form.seas_id" placeholder="请选择客户公海">
                            <el-option v-for="item in seaids" :key="item.id" :value="item.id" :label="item.name">{{
                                item.name
                            }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户来源" prop="source_id">
                        <el-select v-model="form.source_id" placeholder="请选择客户来源">
                            <el-option
                                v-for="item in cust_source"
                                :key="item.id"
                                :value="item.id"
                                :disabled="item.status != 1"
                                :label="item.name"
                                >{{ item.name }}</el-option
                            >
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户阶段" prop="stage_id">
                        <el-select v-model="form.stage_id" placeholder="请选择客户阶段">
                            <el-option v-for="item in cust_stage" :key="item.id" :value="item.id" :label="item.name">{{
                                item.name
                            }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户标签">
                        <el-button size="small" @click="selectTag">选择标签</el-button>
                        <div>
                            <el-tag
                                v-for="tag in cust_list"
                                :key="tag.id"
                                class="cusTag"
                                type="warning"
                                :closable="!(pageType === 'look')"
                                :disable-transitions="false"
                                @close="handleClose(tag)">
                                {{ tag.name }}
                            </el-tag>
                        </div>
                    </el-form-item>
                </el-form>
            </Dialog>
            <BatchLabel ref="BatchLabelRef" @save="getTagsFun"></BatchLabel>
            <el-drawer
                v-model="drawer"
                custom-class="drawer_box"
                :title="detail_title"
                size="55%"
                :direction="direction">
                <div class="content">
                    <el-tabs v-model="activeName" @tab-change="handleClick">
                        <el-tab-pane label="成功" :name="1"> </el-tab-pane>
                        <el-tab-pane label="失败" :name="2"> </el-tab-pane>
                    </el-tabs>
                    <div>
                        <ZwSearchForm
                            ref="searchForm"
                            row-num="3"
                            :option="searchSOption"
                            @search="searchDetail"
                            @reset="resetDetail" />
                        <ZwTable
                            ref="tableRef"
                            class="table-box"
                            :option="tableDetailSucess"
                            :fetch-params="state.searchDetailParams"
                            :fetch-api="fetchStatus()">
                        </ZwTable>
                    </div>
                </div>
            </el-drawer>
            <SendUrl
                :title="title"
                :isopen="isopen"
                :delivery_address="delivery_address"
                :push-url="pushUrl"
                @close="isopen = false">
            </SendUrl>
        </el-card>
    </div>
</template>
<script setup lang="tsx">
import { ref, reactive, computed, nextTick, watch } from 'vue';
import { ElMessage, ElButton, ElMessageBox } from 'element-plus';
import ZwTable from '@/components/zw/table/Table';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import Dialog from '@/components/Dialog.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import BatchLabel from '@/components/BatchLabel.vue';
import SendUrl from '../components/SendUrl.vue';
import { deepCopy } from '@/utils/helper';
import { exportList, clientSeas, newJoint, detail, editJoint, pushList, delJoint, expDetails } from '../api';
import { sourceList, stageList } from '../../configure/api';
import router from '@/router';
const tableRef = ref(null);
const ruleForm = ref();
const BatchLabelRef = ref(null);
const searchForm = ref(null);
const DrawerRef = ref(null);
const isopen = ref(false);
const drawer = ref(false);
const cust_list = ref([]);
const delivery_address = ref([]);
const title = ref();
const seaTitle = ref();
const detail_title = ref();
const defaultParams = {
    name: ''
};
const detailDefault = {
    id: '',
    status: 1
    // keywords: '',
};
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchDetailParams: deepCopy(detailDefault)
});
const params = ref({
    page: 1,
    pre_page: 9999
});
const pushUrl = ref('');
const activeName = ref(1);
const form = reactive({
    name: '',
    seas_id: '',
    source_id: '',
    stage_id: '',
    tag_ids: []
});
const rules = reactive({
    name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
    seas_id: [{ required: true, message: '请选择客户公海', trigger: 'blur' }],
    source_id: [{ required: true, message: '请选择客户来源', trigger: 'blur' }],
    stage_id: [{ required: true, message: '请选择客户阶段', trigger: 'blur' }]
});
// 取消
const cancelHandel = (refresh?: number, text: string) => {
    Object.keys(form).reduce((val, key) => {
        if (key == 'tag_ids') {
            form[key] = [];
        } else if (key == 'id') {
            delete form[key];
        } else {
            form[key] = '';
        }
    }, {});
    if (refresh == 1) {
        ElMessage.success(text);
        state.searchParams = { ...state.searchParams };
    }
    cust_list.value = [];
    appDialog.visible = false;
};
//确定
const submitHandel = async () => {
    if (!ruleForm.value) return;
    await ruleForm.value.validate((valid, fields) => {
        if (valid) {
            if (form.id) {
                editJoint(form).then((res: any) => {
                    cancelHandel(1, '编辑成功');
                });
            } else {
                newJoint(form).then((res: any) => {
                    cancelHandel(1, '新建成功');
                });
            }
        }
    });
};
const appDialog = reactive({
    visible: false,
    title: seaTitle,
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});
const tableOption = [
    {
        prop: 'name',
        label: '规则名称'
    },
    {
        prop: 'seas_name',
        label: '关联公海'
    },
    {
        label: '成功数量/失败客户数',
        prop: 'execute_workuser',
        render({ row, column, index }) {
            return row.success_import_num + '/' + row.fail_import_num;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 330,
        fixed: 'right',
        isOperate: true,
        render({ row }) {
            const btnList = [
                { id: 1, text: '编辑' },
                { id: 2, text: '推送地址' },
                { id: 3, text: '删除' },
                { id: 4, text: '导入明细' }
            ];
            return (
                <>
                    {btnList.map((item: any) => {
                        return (
                            <ElButton size="small" onClick={() => operate(item.id, row)}>
                                {item.text}
                            </ElButton>
                        );
                    })}
                </>
            );
        }
    }
];
const tableDetailSucess = [
    {
        prop: 'cust_id',
        label: '客户ID'
    },
    {
        prop: 'cust_name',
        label: '客户名称',
        render({ row }) {
            return <p>{row.cust_name ? row.cust_name : '--'}</p>;
        }
    },
    {
        prop: 'cust_phone',
        label: '手机号'
    },
    {
        prop: 'distribution_name',
        label: '分配情况'
        // render({ row, column, index }) {
        //   if (row.distribution_status == 1) {
        //     return '待分配'
        //   } else {
        //     return '已分配'
        //   }
        // }
    },
    {
        prop: 'created_at',
        label: '入库时间'
    }
];
const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称'
        }
    ];
});
const searchSOption = computed(() => {
    return [
        {
            label: '',
            name: 'keywords',
            value: '',
            type: 'input',
            placeholder: '请输入客户名称｜手机号搜索'
        }
    ];
});
const seaids = ref([]); //客户公海列表
const cust_source = ref([]); // 客户来源
const cust_stage = ref([]); // 客户阶段
//获取公海列表
const getSeaList = () => {
    clientSeas({ page: 1, page_size: 9999 }).then((res: any) => {
        seaids.value = res;
    });
};
// 获取客户来源
const getCust_source = () => {
    sourceList(params.value).then((res: any) => {
        cust_source.value = res.data;
    });
};
// 获取客户阶段
const getCust_stage = () => {
    stageList(params.value).then((res: any) => {
        cust_stage.value = res;
    });
};
// 选择客户标签
const selectTag = () => {
    BatchLabelRef.value!.dialogVisible = true;
};
// 获取选中的客户标签
const getTagsFun = (data: any) => {
    cust_list.value = data.data;
    form.tag_ids = data.idList;
};
// 移除客户标签
const handleClose = (val: any) => {
    const i = form.tag_ids.findIndex((n: any) => n == val.id);
    cust_list.value.splice(i, 1);
    form.tag_ids.splice(i, 1);
};
const newImport = async (row?: any) => {
    await getSeaList();
    await getCust_source();
    await getCust_stage();
    if (row) {
        seaTitle.value = '编辑对接';
        getDetail(row);
    } else {
        seaTitle.value = '新建对接';
    }
    appDialog.visible = true;
};
// 获取链接详情
const getDetail = (row_id: number) => {
    detail({ id: row_id }).then((res: any) => {
        Object.keys(form).reduce((val, key) => {
            form[key] = res[key];
        }, {});
        cust_list.value = res.tag_name;
    });
};
// 操作按钮
const operate = (n: number, row: any) => {
    switch (n) {
        case 1:
            newImport(row.id);
            form.id = row.id;
            break;
        case 2:
            pushList().then((res: any) => {
                isopen.value = true;
                title.value = row.name;
                pushUrl.value = row.push_address;
                delivery_address.value = res;
            });
            break;
        case 3:
            ElMessageBox.confirm(`您确认要删除【${row.name}】的规则吗？删除后第三方的数据将停止自动导入？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delJoint({ id: row.id }).then(() => {
                    cancelHandel(1, '删除成功');
                });
            });
            break;
        case 4:
            detailDefault.id = row.id;
            activeName.value = 1;
            detail_title.value = row.name;
            drawer.value = true;
            resetDetail();
            break;
    }
};
// 获取第三方接入列表
const fetch = () => {
    return exportList;
};
//第三方接入列表查询
const search = (v: any) => {
    state.searchParams = v;
};
//导入明细查询
const searchDetail = (v: any) => {
    state.searchDetailParams = deepCopy(v);
};
//第三方接入列表清空
const reset = () => {
    state.searchParams = deepCopy(defaultParams);
};
//导入明细清空
const resetDetail = (v?: any) => {
    state.searchDetailParams = deepCopy(detailDefault);
};
const getids = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(detailDefault);
        }, 1);
    });
};
// 获取导入明细列表
const fetchStatus = async () => {
    const id = await getids();
    // const keywords = state.searchDetailParams.keywords
    return [id, expDetails];
};
//导入明细tab切换
const handleClick = (data: any) => {
    // searchForm.value!.reset()
    detailDefault.status = activeName.value;
    state.searchDetailParams = deepCopy(detailDefault);
};
watch(
    () => activeName.value,
    val => {
        if (val == 2) {
            const obj = {
                prop: 'fail_reason',
                label: '失败原因',
                render({ row }) {
                    return <p>{row.fail_reason ? row.fail_reason : '--'}</p>;
                }
            };
            tableDetailSucess.splice(3, 1, obj);
        } else {
            const obj2 = {
                prop: 'distribution_name',
                label: '分配情况'
                // render({ row, column, index }) {
                //   if (row.distribution_status == 1) {
                //     return '待分配'
                //   } else {
                //     return '已分配'
                //   }
                // }
            };
            tableDetailSucess.splice(3, 1, obj2);
        }
    }
);
</script>
<style scoped lang="scss">
.addForm {
    margin-top: 14px;

    .el-select {
        width: 100%;
    }

    :deep(.cusTag) {
        height: 22px;
        line-height: 20px;
        font-size: 14px;
        color: #ff6b00;
        margin-right: 6px;
        border: 1px solid #ffc69e;
        background-color: #fffaf9;
    }
}
</style>
